package com.gitee.huanminabc.jcommon.encryption;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class BaseAesHelp {
    public static final String AES = "AES";
    public static final String AES_CBC_PKCS5PADDING = "AES/CBC/PKCS5Padding";
    public static final String AES_EBC_PKCS5PADDING = "AES/ECB/PKCS5Padding";
    private static final int KEY_LENGTH_16 = 16;
    private static final int KEY_LENGTH_32 = 32;
    /**
     * 检查key是否合法
     *
     * @param key {@link String}秘钥信息
     * @throws Exception 异常信息
     */
    public  static void checkKey(String key) throws Exception {
        if (key == null || key.length() != KEY_LENGTH_16 && key.length() != KEY_LENGTH_32) {
            throw new Exception("加密秘钥不正确,必须为16位或32位");
        }
    }

    /**
     * 检查偏移矢量是否合法
     *
     * @param iv {@link String} 偏移矢量
     * @throws Exception 异常信息
     */
    public static void checkIV(String iv) throws Exception {
        if (iv == null || iv.length() != KEY_LENGTH_16) {
            throw new Exception("偏移矢量不正确，必须为16位");
        }
    }
    public static void checkKeyAndIV(String key,String iv) throws Exception {
        checkKey(key);
        checkIV(iv);
    }



    //秘钥生成 16位
    public static String getKey() {
        String key= UUID.randomUUID().toString();
        // 密钥补位
        int plus= 16-key.length();
        byte[] data = key.getBytes(StandardCharsets.UTF_8);
        byte[] raw = new byte[16];
        byte[] plusbyte={ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
        for(int i=0;i<16;i++)
        {
            if (data.length > i)
                raw[i] = data[i];
            else
                raw[i] = plusbyte[plus];
        }
        return new String(raw, StandardCharsets.UTF_8);
    }

}
